package com.digitalchina.lxnsy.service;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.activity.farmTrain.DemandListActivity;
import com.digitalchina.lxnsy.activity.farmTrain.MyDemandListActivity;
import com.digitalchina.lxnsy.activity.farmTrain.MyQuoteListActivity;
import com.digitalchina.lxnsy.activity.old.ActivityDetailActivity;
import com.digitalchina.lxnsy.activity.old.AgriculturalServiceDetailActivity;
import com.digitalchina.lxnsy.activity.old.AgriculturalTrainingDetailsActivity;
import com.digitalchina.lxnsy.activity.old.FarmingInfoDetailActivity;
import com.digitalchina.lxnsy.activity.old.MainActivity;
import com.digitalchina.lxnsy.activity.old.ShareFarmDetailActivity;
import com.digitalchina.lxnsy.activity.old.TechnologiesDetailActivity;
import com.digitalchina.lxnsy.activity.old.TrainEvaluateNewLocalDataActivity;
import com.digitalchina.lxnsy.constant.Constant;
import com.digitalchina.lxnsy.fragment.MainHomePageV3Fragment;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;

/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class JPushReceiver extends BroadcastReceiver {
    private static final String TAG = "JPush";

    @Override
    public void onReceive(Context context, Intent intent) {
        Bundle bundle = intent.getExtras();
        Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));

        if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
            String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
            Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
            //send the Registration Id to your server...

        } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
            LogUtils.e(bundle.getString(JPushInterface.EXTRA_MESSAGE));
//            Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));

            //ToastUtil.showToast(context,"您有新消息，请在通知列表查看。");
        } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
            int notifactionId = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
            Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId);

        } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户点击打开了通知");

            openNotification(context, bundle);

        } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
            Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
            //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

        } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
            boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
            Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
        } else {
            Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
        }
    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:").append(key).append(", value: [").append(myKey).append(" - ").append(json.optString(myKey)).append("]");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:").append(key).append(", value:").append(bundle.getString(key));
            }
        }
        return sb.toString();
    }

    /**
     * 用户点击打开Notification
     *
     * @param context 上下文
     * @param bundle  推送内容
     */
    private void openNotification(Context context, Bundle bundle) {
        String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
        String type = "";
        String contentId = "";
        try {
            JSONObject extrasJson = new JSONObject(extras);
            String json = new JSONObject(extrasJson.toString()).getString("extra");
            if (new JSONObject(json).has("newApp"))
                goToActivity(context, MainActivity.class);
            else {
                type = new JSONObject(json).getString("type");
                contentId = new JSONObject(json).getString("content");
            }
        } catch (Exception e) {
            LogUtils.e("Unexpected: extras is not a valid json");
            return;
        }

        switch (type) {
            case Constant.JPUSH_TYPE_EVALUATE:  // 评价提醒
                go(context, TrainEvaluateNewLocalDataActivity.class, "JPush_evaluate", contentId);
                break;
            case Constant.JPUSH_TYPE_ATTENTION: //关注提醒
                go(context, AgriculturalTrainingDetailsActivity.class, "JPush_attention", contentId);
                break;
            case Constant.JPUSH_TYPE_AGRICULTURAL_SERVICE: // 农事服务
                go(context, AgriculturalServiceDetailActivity.class, "JPush_service", contentId);
                break;
            case Constant.JPUSH_TYPE_TECHNOLOGIES: // 技术大全
                go(context, TechnologiesDetailActivity.class, "contentId", contentId);
                break;
            case Constant.JPUSH_TYPE_ACTIVITY: // 活动
                go(context, ActivityDetailActivity.class, "contentId", contentId);
                break;
            case "6": // 农事资讯
                go(context, FarmingInfoDetailActivity.class, "contentId", contentId);
                break;
            case "7": // 共享资源
                go(context, ShareFarmDetailActivity.class, "contentId", contentId);
                break;
            case "8": // 匹配机构推送培训需求提醒
                go(context, DemandListActivity.class, "contentId", contentId);
                break;
            case "9": // 培训机构报价给需求方提醒
                go(context, MyDemandListActivity.class, "contentId", contentId);
                break;
            case "10": // 培训机构被选中提醒
                go(context, MyQuoteListActivity.class, "contentId", contentId);
                break;
            case "11": // 培训机构被淘汰提醒
                go(context, MyQuoteListActivity.class, "contentId", contentId);
                break;

        }
    }

    private void goToActivity(Context context, Class<?> pClass) {
        Intent intent = new Intent(context, pClass);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

    private void go(Context context, Class<?> pClass, String key, Object obj) {
        Intent intent = new Intent(context, pClass);
        intent.putExtra(key, (Serializable) obj);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        context.startActivity(intent);
    }

}
